package com.ruoyi.order.service;

import com.ruoyi.order.domain.Orders;
import com.ruoyi.order.domain.UserCoupon;
import com.ruoyi.order.mapper.OrdersMapper;
import com.ruoyi.order.mapper.UserCouponMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.amqp.core.Message;
import com.rabbitmq.client.Channel;

@Service
public class OrderConsumer {


    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private OrderProducer orderProducer;
    // 将对数据库的操作异步执行，提高系统的响应速度和并发能力
    @RabbitListener(queues = "q1")
    @Transactional
    public void receiveOrder(Orders msg, Channel channel, Message message) {
        try {
            System.out.println("生成订单：");
            // 处理订单逻辑，如扣减库存、生成物流信息等
            System.out.println(msg);
            // 判断当前时间是否在订单的预约时间范围内
            ordersMapper.insertOrders(msg);
            // 修改优惠券的状态
            UserCoupon userCoupon = userCouponMapper.selectUserCouponByUcId(msg.getUcId());
            if (userCoupon.getStatus() == 1L) {
                // 订单状态为已完成，修改优惠券的状态
                userCouponMapper.updateUserCouponByUcId(msg.getUcId(), 2L);
            }else {
                throw new RuntimeException("优惠券状态异常");
            }
            // 手动确认消息，消费成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                System.out.println("消息处理失败，无法手动确认消息");
                // 手动拒绝消息，且不重新入队，即丢弃消息
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            } catch (Exception ex) {
                System.out.println("消息处理失败，无法手动拒绝消息");
            }
            throw new RuntimeException("订单处理失败", e);
        }
    }

    // 监听死信队列
    @RabbitListener(queues = "dlxQueue")
    public void receiveDlxOrder(Orders msg) {
        System.out.println("死信队列接收到消息：");
        // 处理订单逻辑，如扣减库存、生成物流信息等
        System.out.println(msg);
        System.out.println(msg.getOrderNum());
        Orders orders = ordersMapper.selectOrdersBynum(msg.getOrderNum());
        // 如果订单状态为未支付，则取消订单
        // 0-待支付，1-已完成，2-已取消, 3-已退款， 4-待核销，
        System.out.println(orders);
        if (orders != null && orders.getOrderStatus() == 0) {
            orders.setOrderStatus(2L);
            ordersService.updateOrders(orders);
        }
    }
}